package gui;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.swing.JComponent;

import facade.CrossRoadInfo;
import facade.RoadInfo;
import facade.TrafficInfrastructureFacade;


public class DrawArea extends JComponent {

	private TrafficInfrastructureFacade infrastructure;
	
	public DrawArea(TrafficInfrastructureFacade t) {
		infrastructure = t;
		setRefreshNeeded(true);
		t.subscribeChangeObserver(
			new TrafficInfrastructureFacade.TrafficChangeObserver() {
				public void notifyTrafficChange() {
					setRefreshNeeded(true);
					repaint();
				}
			}
		);
	}
	
	private void setRefreshNeeded(boolean val) {
		refreshNeeded = val;
	}
	
	private boolean isRefreshNeeded() {
		return refreshNeeded;
	}
	
	private boolean refreshNeeded;
	
	public void refreshDisplayedObjects() {
		displayedObjects = new ArrayList<DisplayedObject>();
		//voeg objecten om weer te geven toe		
		Collection<CrossRoadInfo> crs = infrastructure.getAllCrossRoads();
		for(CrossRoadInfo cr : crs) {
			displayedObjects.add(new DisplayedCrossRoad(cr));
		}
		
		Collection<RoadInfo> rs = infrastructure.getAllRoads();
		for(RoadInfo r : rs) {
			displayedObjects.add(new DisplayedRoad(r));
		}
		setRefreshNeeded(false);
	}
	
	/* This gets called when the panel needs to be repainted.
	 */
	@Override
	public void paintComponent(Graphics g) {
		if(isRefreshNeeded()) refreshDisplayedObjects();
		super.paintComponent(g);
		Graphics2D g2d = (Graphics2D)g;
		g2d.translate(50, 50);
		g2d.scale(50,50);
		g2d.setColor(Color.BLACK);
		g2d.setStroke(new BasicStroke(0.1f));
		Collection<DisplayedObject> objs = new ArrayList<DisplayedObject>(displayedObjects);
		for(DisplayedObject d : objs) {
			d.draw(g2d);
		}
	}
	
	private List<DisplayedObject> displayedObjects = new ArrayList<DisplayedObject>();
	private static final long serialVersionUID = 1L;

}
